package com.my.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.my.annotation.SystemErrorLog;
import com.my.common.IdcardInfoExtractor;
import com.my.common.MobileFromUtil;
import com.my.constant.ErrorCode;
import com.my.entity.Employee;
import com.my.entity.ResponseData;
import com.my.service.CommonService;
import com.my.service.EmployeeService;
import com.my.util.CookieUtil;

@Controller
@RequestMapping(value = "/common")
public class CommonAction {
    private static final Logger logger = LoggerFactory.getLogger(CommonAction.class);
	@Resource
	CommonService commonService;
	@Resource
	private EmployeeService employeeService;

	
	@RequestMapping(value = "export_excel")
	@SystemErrorLog(description="导出Excel失败")
	public String exportExcel(HttpServletRequest request,
			HttpServletResponse response) {
		String fileName = "excel文件";
		String columnNames[] = { "ID", "项目名", "销售人", "负责人", "所用技术", "备注" };// 列名
		String keys[] = { "id", "name", "saler", "principal", "technology",
				"remarks" };// map中的key
		commonService.exportExcel(request, response, fileName, columnNames,
				keys);
		return null;
	}

	@SystemErrorLog(description="上传文件失败")
	@RequestMapping("/upload")
	public String upload(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		// 这里我用到了jar包
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (multipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				MultipartFile file = multiRequest.getFile((String) iter.next());
				if (file != null) {
					String fileName = file.getOriginalFilename();
					String path1 = Thread.currentThread()
							.getContextClassLoader().getResource("").getPath()
							+ "download" + File.separator;
					// 下面的加的日期是为了防止上传的名字一样
					String path = path1
							+ new SimpleDateFormat("yyyyMMddHHmmss")
									.format(new Date()) + fileName;
					File localFile = new File(path);
					file.transferTo(localFile);
				}
			}
		}
		return "uploadSuccess";
	}

	@SystemErrorLog(description="下载文件失败")
	@RequestMapping("/download")
	public String download(String fileName, HttpServletRequest request,
			HttpServletResponse response) {
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		response.setHeader("Content-Disposition", "attachment;fileName="
				+ fileName);
		try {
			String path = Thread.currentThread().getContextClassLoader()
					.getResource("").getPath()
					+ "download";// 这个download目录为啥建立在classes下的
			InputStream inputStream = new FileInputStream(new File(path
					+ File.separator + fileName));

			OutputStream os = response.getOutputStream();
			byte[] b = new byte[2048];
			int length;
			while ((length = inputStream.read(b)) > 0) {
				os.write(b, 0, length);
			}

			// 这里主要关闭。
			os.close();
			inputStream.close();
		} catch (FileNotFoundException e) {
//			e.printStackTrace();
			logger.error("下载文件失败：文件未找到", e);
		} catch (IOException e) {
//			e.printStackTrace();
			logger.error("下载文件失败", e);
		}
		// 返回值要注意，要不然就出现下面这句错误！
		// java+getOutputStream() has already been called for this response
		return null;
	}
	
	@SystemErrorLog(description="通过身份证获取地址失败")
	@RequestMapping("/get_address_by_idCard")
	public @ResponseBody ResponseData<IdcardInfoExtractor> getAddressAndSexByIdCard(
			String idCard) {
		try {
			IdcardInfoExtractor idcardInfoExtractor = new IdcardInfoExtractor(
					idCard);
			List<IdcardInfoExtractor> addressAndSex = new ArrayList<IdcardInfoExtractor>();
			addressAndSex.add(idcardInfoExtractor);
			return new ResponseData<IdcardInfoExtractor>(ErrorCode.SUCCESS,
					ErrorCode.SUCCESS.getDesc(), addressAndSex, false, null);
		} catch (Exception e) {
//			e.printStackTrace();
			logger.error("通过身份证获取地址信息失败",e);
			return new ResponseData<IdcardInfoExtractor>(ErrorCode.FAUILURE,
					ErrorCode.FAUILURE.getDesc(), null, true, null);
		}
	}
	
	@SystemErrorLog(description="通过手机号得到商家失败")
	@RequestMapping("/get_phone_supplier")
	public @ResponseBody ResponseData<String> getPhoneSupplier(String phone) {
		try {
			String result = MobileFromUtil.calcMobileCity(phone);
			return new ResponseData<String>(ErrorCode.SUCCESS,
					ErrorCode.SUCCESS.getDesc(), null, false, result);
		} catch (Exception e) {
//			e.printStackTrace();
			logger.error("通过手机号得到商家失败",e);
			return new ResponseData<String>(ErrorCode.FAUILURE,
					ErrorCode.FAUILURE.getDesc(), null, true, null);
		}
	}
	
	@SystemErrorLog(description="保存Cookie失败")
	@RequestMapping("/save_cookie")
	public String saveCookie(HttpServletResponse response,
			String url, String lang) {
		CookieUtil.saveCookie("lang", lang, response);
		return "redirect:" + url;
	}

	
	@RequestMapping("/query_is_delete")
	public String queryIsDeleteData(HttpServletRequest request) {
		List<Employee> empList=employeeService.queryIsDeleteEmp();
		request.setAttribute("empList", empList);
		return "common/is_delete_data";
	}
}
